package ru.gerunn.test.jndi;

import javax.naming.NamingException;
import javax.naming.spi.NamingManager;

public class JNDIUtil {
	public void initializeJNDI() {
		if (jndiInitialized()) {
			cleanAllInMemoryData();
		} else {
			installDefaultContextFactoryBuilder();
		}
	}

	private boolean jndiInitialized() {
		return NamingManager.hasInitialContextFactoryBuilder();
	}

	private void installDefaultContextFactoryBuilder() {
		try {
			NamingManager.setInitialContextFactoryBuilder(new CloseSafeMemoryContextFactoryBuilder());
		} catch (NamingException e) {
			// We can not solve the problem. We will let it go up without
			// having to declare the exception every time.
			// throw new ConfigurationException();
		}
	}

	private void cleanAllInMemoryData() {
		CleanerContext cleaner = new CleanerContext();
		try {
			cleaner.close();
		} catch (NamingException e) {
			throw new RuntimeException("Memory context cleaning failed:", e);
		}
	}
}
